package com.example.clinetoffline.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.example.mapper.MessageRemindMapper;
import com.example.mapper.OmDeviceOfflineRecordMapper;
import com.example.mapper.infoMapper;
import com.example.pojo.AlarmMassage;
import com.example.pojo.OmDeviceofflinerecord;
import com.example.clinetoffline.service.ClientOfflineService;
import com.example.pojo.dev.icDevState;
import com.example.pojo.alarm.messageRemind;
import com.example.pojo.dev.fmDevInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: client offline warning
 * @description: state表设备下线后警示弹窗
 * @author: xingzh
 * @create: 2022-09-01 14:34
 **/
@Component
public class AlarmThread implements Runnable {

    static public ClientOfflineService clientOfflineService;

    @Autowired
    public void stateMapper(ClientOfflineService clientOfflineService) {
        AlarmThread.clientOfflineService = clientOfflineService;
    }

    static public infoMapper infoMapper;

    @Autowired
    public void infoMapper(infoMapper infoMapper) {
        AlarmThread.infoMapper = infoMapper;
    }

    static public OmDeviceOfflineRecordMapper omDeviceofflinerecordMapper;

    @Autowired
    public void omDeviceofflinerecordMapper(OmDeviceOfflineRecordMapper omDeviceofflinerecordMapper) {
        AlarmThread.omDeviceofflinerecordMapper = omDeviceofflinerecordMapper;
    }
    static public MessageRemindMapper messageRemindMapper;
    @Autowired
    public void messageRemindMapper(MessageRemindMapper messageRemindMapper) {
        AlarmThread.messageRemindMapper = messageRemindMapper;
    }

    private boolean flag = true;

    private Map<Integer, String> map = new ConcurrentHashMap<>();

    @Override
    public void run() {
        while (flag) {
            //读取数据库里的state表中数据
            List<icDevState> stateList = clientOfflineService.getAll();
            //遍历数据表中取出的数据,并存入map
            for (icDevState s : stateList) {
                map.put(s.getId(), s.getSingal());
            }
            try {
                //间隔5秒
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //再读取数据库里的数据
            stateList = clientOfflineService.getAll();
            //将警告列表置空
            List<fmDevInfo> deviceinfoList = new ArrayList<>();
            ArrayList<AlarmMassage> alarmMassages = new ArrayList<>();
            for (icDevState s : stateList) {
                //如果状态不是在线的话,则检查它五秒前是什么状态.如果是未在线状态,则不警告;如果是在线,则它是第一次离线,需要警告
                if (!s.getSingal().equals("Good")) {
                    //5秒前它的状态
                    String oldSignal = map.get(s.getId());
                    if (oldSignal.equals("Good")) {
                        //根据dbid和modelid去找fm_deviceinfo表里的dev_name,dev_location,subsystem_belong
                        fmDevInfo fmDeviceinfo = infoMapper.selectdevicebyobjectId(String.valueOf(s.getDbId()), s.getModelId());
                        //如果最近有一条一分钟以内离线的数据，则不添加到消息提醒列表
                        OmDeviceofflinerecord lastOffline = omDeviceofflinerecordMapper.isLogExist(s.getDbId(), Integer.valueOf(s.getModelId()));
                        boolean addFlag = true;
                        if (lastOffline != null && (DateUtil.betweenMs(lastOffline.getOfflineTime(), new Date()) < 1000 * 60)) {
                            addFlag = false;
                        }
                        //添加离线日志
                        OmDeviceofflinerecord omDeviceofflinerecord = new OmDeviceofflinerecord();
                        omDeviceofflinerecord.setDbId(s.getDbId());
                        omDeviceofflinerecord.setModelId(Integer.valueOf(s.getModelId()));
                        omDeviceofflinerecord.setOfflineTime(new Date());
                        omDeviceofflinerecordMapper.insert(omDeviceofflinerecord);
                        //将设备对象存储到警告列表
                        if (addFlag){
                            deviceinfoList.add(fmDeviceinfo);
                        }
                    }
                } else {
                    //如果是在线，则查看记录表中是否填写了上线时间
                    //读取om_deviceofflinerecord表中数据
                    OmDeviceofflinerecord offlineRecord = omDeviceofflinerecordMapper.isLogExist(s.getDbId(),Integer.valueOf(s.getModelId()));
                    if (offlineRecord != null) {
                        if (offlineRecord.getOnlineTime() == null){
                            //如果上线时间没有填写，则更新上线时间为当前时间
                            omDeviceofflinerecordMapper.updateOnlineTimeByDbId(new Date(), s.getDbId(), Integer.valueOf(s.getModelId()));
                            messageRemindMapper.updateIsResetByDbIdModelId(s.getDbId(),Integer.valueOf(s.getModelId()),true);
                        }
                    }
                    //如果状态是在线，则判断它五秒前是不是离线状态
                    String oldSignal = map.get(s.getId());
                    if (!oldSignal.equals("Good")) {
                        //如果五秒钟前它不是在线状态，则刚刚上线
                        //判断这个日志是否存在
                        if (omDeviceofflinerecordMapper.isLogExist(s.getDbId(), Integer.valueOf(s.getModelId())) != null) {
                            //根据dbid和modelid去找fm_deviceinfo表里的dev_name,dev_location,subsystem_belong
                            fmDevInfo fmDeviceinfo = infoMapper.selectdevicebyobjectId(String.valueOf(s.getDbId()), s.getModelId());
                            //更新离线日志
                            omDeviceofflinerecordMapper.updateOnlineTimeByDbId(new Date(), s.getDbId(), Integer.valueOf(s.getModelId()));
                            //更新上线
                            messageRemind messageRemind = new messageRemind();
                            messageRemind.setOrderType("设备离线提醒");
                            messageRemind.setDevLocation(fmDeviceinfo.getDevLocation());
                            messageRemind.setFaultLevel("一般");
                            messageRemind.setAlarmSatus("离线");
                            messageRemind.setDevName(fmDeviceinfo.getDevName());
                            messageRemind.setDevNumber(fmDeviceinfo.getDevNumber());
                            messageRemind.setLastrecialamtime(new Date());
                            messageRemind.setIsReset(true);
                            messageRemind.setAlarmType("offline");
                            messageRemind.setDbId(Integer.parseInt(fmDeviceinfo.getObjectId()));
                            messageRemind.setModelId(Integer.parseInt(fmDeviceinfo.getModelId()));
                            messageRemind.setAlarmnumber(1);
                            messageRemind.setSubsystemBelong(fmDeviceinfo.getSubsystemBelong());
                            messageRemind.setSystemBelong(fmDeviceinfo.getSystemBelong());
                            messageRemind.setLocation(fmDeviceinfo.getDevLocation());
                            messageRemind select = messageRemindMapper.select(messageRemind);
                            if (select != null){
                                messageRemind.setId(select.getId());
                                messageRemindMapper.updatalarmnumber(messageRemind);
                            }
                        }
                    }
                }
            }
            //如果警告列表不为空,则发出警告
            if (CollectionUtil.isNotEmpty(deviceinfoList)) {
                AlarmMassage alarmMassage = new AlarmMassage();
                alarmMassage.setMaintainType("设备离线");
                //遍历列表
                for (fmDevInfo device : deviceinfoList) {

                    //消息提醒存储
                    messageRemind messageRemind = new messageRemind();
                    //设备报警
                    messageRemind.setOrderType("设备离线提醒");
                    messageRemind.setDevLocation(device.getDevLocation());
                    messageRemind.setFaultLevel("一般");
                    messageRemind.setAlarmSatus("离线");
                    messageRemind.setDevName(device.getDevName());
                    messageRemind.setDevNumber(device.getDevNumber());
                    messageRemind.setLastrecialamtime(new Date());
                    messageRemind.setIsReset(false);
                    messageRemind.setAlarmType("offline");
                    messageRemind.setDbId(Integer.parseInt(device.getObjectId()));
                    messageRemind.setModelId(Integer.parseInt(device.getModelId()));
                    messageRemind.setAlarmnumber(1);
                    messageRemind.setSubsystemBelong(device.getSubsystemBelong());
                    messageRemind.setSystemBelong(device.getSystemBelong());
                    messageRemind.setLocation(device.getDevLocation());

                    messageRemind select = messageRemindMapper.select(messageRemind);
                    if (select!=null){
                        messageRemind.setId(select.getId());
                        messageRemindMapper.updatalarmnumber(messageRemind);
                    }else {
                        messageRemindMapper.insertmessageRemind(messageRemind);
                    }



                    alarmMassage.setDevNumber(device.getDevNumber());
                    alarmMassage.setDevLocation(device.getDevLocation());
                    alarmMassage.setDevName(device.getDevName());
                    alarmMassages.add(alarmMassage);
                }
                HashMap<Object, Object> map = new HashMap<>();
                map.put("offline", alarmMassages);
                //   WebSocketServerRemind.sendMessage(JSONArray.toJSONString(map));
            }
        }
    }
}
